package encryption;


// StringEncryptorToBigInt.java 
// Let the user enter a string and password-key.  Encrypt the string
// into a file using the DES secret key algorithm.  This time,
// however, the encrypted file is text, namely the String form of a
// BigInteger representation of the byte stream for the encryption.
import java.io.*;
import java.math.*;
import java.util.*;
import java.security.*;
import java.security.spec.*;
import javax.crypto.*;
import javax.crypto.spec.*;

public class StrEnToBI {

	public static String EncryptBI(String encrypt, String pass) {

		String the_string = encrypt;
		String password = pass;

		while (password.length() < 8) { 
			password += " ";
		}

		try {
			InputStream in = new ByteArrayInputStream(the_string.getBytes());

			// Create a key.
			byte[] desKeyData = password.getBytes();
			DESKeySpec desKeySpec = new DESKeySpec(desKeyData);
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
			SecretKey desKey = keyFactory.generateSecret(desKeySpec);

			// Use Data Encryption Standard cipher
			Cipher des = Cipher.getInstance("DES");
			des.init(Cipher.ENCRYPT_MODE, desKey);

			ArrayList<Byte> enc_bytes = new ArrayList<Byte>();

			byte[] input = new byte[64];
			while (true) {
				int bytesRead = in.read(input);
				if (bytesRead == -1)
					break;
				byte[] output = des.update(input, 0, bytesRead);
				if (output != null)
					for (int i = 0; i < output.length; i++)
						enc_bytes.add(new Byte(output[i]));
			}

			byte[] output = des.doFinal();
			if (output != null)
				for (int i = 0; i < output.length; i++)
					enc_bytes.add(new Byte(output[i]));
			in.close();
			Object enc_data_wrap[] = enc_bytes.toArray();
			byte enc_data[] = new byte[enc_data_wrap.length];
			for (int i = 0; i < enc_data_wrap.length; i++)
				enc_data[i] = ((Byte) enc_data_wrap[i]).byteValue();
			BigInteger bi = new BigInteger(enc_data);
			return bi.toString();
			
		} catch (InvalidKeySpecException e) {
			System.err.println(e);
		} catch (InvalidKeyException e) {
			System.err.println(e);
		} catch (NoSuchAlgorithmException e) {
			System.err.println(e);
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			System.err.println(e);
		} catch (BadPaddingException e) {
			System.err.println(e);
		} catch (IllegalBlockSizeException e) {
			System.err.println(e);
		} catch (IOException e) {
			System.err.println(e);
		}

		return "Encryption Failed";
	}
}
